import { getCurrentUserActionList, subLogin } from '@/services/user/login';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { Alert, Tabs } from 'antd';
import { useState, useEffect } from 'react';
// @ts-ignore
import QRCode from 'qrcode.react';
import styles from './style.less';
import { getPadQrCode, getQrCodeLoginStatus } from '@/services/common/api';
import { showMsg } from '@/utils/utils';

/** Pad登录。院外登录共用 */
const SubUserLogin = () => {

  const [errorMsg, setErrorMsg] = useState<string>();
  const [tabType, setTabType] = useState<string>('qrcode');
  const [qrCode, setQrCode] = useState<string>('');
  const [tokenResult, setTokenResult] = useState<string | null>(null);

  const goto = async () => {
    const actionList = await getCurrentUserActionList();
    const buttonIdList = actionList.map((item: any) => {
      return item.button_id;
    });
    localStorage.setItem('buttonIdList', JSON.stringify(buttonIdList));
    location.href = '/';
  };

  const onFinish = async (values: Record<string, any>) => {
    setErrorMsg(undefined);
    subLogin({ ...values }).then(res => {
      if (res.token) {
        localStorage.setItem('Oper-Token', res.token);
        goto();
      } else {
        localStorage.setItem('Oper-Token', '');
        setErrorMsg('登录失败');
      }
    }).catch(error => {
      setErrorMsg(error?.data?.errmsg);
    });
  };

  // 扫码结果查询
  const resultQuery = (token: string) => {
    getQrCodeLoginStatus(token).then(({ status }) => {
      if (status === '2') {
        setTokenResult(null);
        localStorage.setItem('Oper-Token', token);
        goto();
      }
    }).catch(err => {
      console.error(err);
    });
  }

  // 定时查询扫码结果
  const resultQueryTime = 3000;
  useEffect(() => {
    if (tokenResult != null) {
      const id = setInterval(resultQuery, resultQueryTime, tokenResult);
      return () => clearInterval(id);
    }
    return () => { };
  }, [tokenResult]);

  // 二维码获取
  const refreshQrCode = () => {
    setTokenResult(null);
    getPadQrCode().then(({ scanUrl, token }) => {
      setQrCode(scanUrl);
      setTokenResult(token ?? null);
    }).catch(err => {
      showMsg(err?.data?.errmsg);
    });
  }

  // 定时获取新的二维码
  const refreshQrCodeTime = 180000;
  useEffect(() => {
    setTokenResult(null);
    if (tabType === 'qrcode') {
      refreshQrCode();
      const id = setInterval(refreshQrCode, refreshQrCodeTime);
      return () => clearInterval(id);
    }
    return () => { };
  }, [tabType]);

  return (
    <div className={styles.loginPage}>
      <div className='form-container'>
        {
          errorMsg && <LoginMessage content={errorMsg} />
        }
        <div className='logo'>
          <UserOutlined style={{ fontSize: 96 }} />
        </div>
        <Tabs activeKey={tabType} onChange={setTabType}>
          <Tabs.TabPane key="qrcode" tab={'扫码登录'} />
          <Tabs.TabPane key="account" tab={'密码登录'} />
        </Tabs>
        {
          tabType === 'account' && <>
            <ProForm
              submitter={{
                searchConfig: { submitText: '登录' },
                render: (_, dom) => dom.pop()
              }}
              onFinish={onFinish}
            >
              <ProFormText
                name="username"
                placeholder='账号'
                fieldProps={{ size: 'large', prefix: <UserOutlined /> }}
                rules={[{ required: true, message: '请输入登录账号!' }]}
              />
              <ProFormText.Password
                name="password"
                placeholder='密码'
                fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
                rules={[{ required: true, message: '请输入密码！' }]}
              />
            </ProForm>
          </>
        }
        {
          tabType === 'qrcode' &&
          <div className='qrcode'>
            <QRCode
              value={qrCode}
              size={245}
              includeMargin={true}
              fgColor="#000"
              renderAs="svg"
            />
          </div>
        }
      </div>
    </div>
  );
};

export default SubUserLogin;

const LoginMessage = ({ content }: { content: string; }) => (
  <Alert
    style={{ marginBottom: 24 }}
    message={content}
    type="error"
    showIcon
  />
);
